package edu.sysu.demo.petstore.dog.config;

import edu.sysu.demo.petstore.dog.data.entity.Key.KeyType;
import edu.sysu.demo.petstore.dog.key.KeyService;
import java.security.PrivateKey;
import java.security.PublicKey;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
class KeyStoreInitializer implements InitializingBean {

  private static final String KEY_NAME = "issue_key";

  private final KeyService keyService;

  @Autowired
  public KeyStoreInitializer(KeyService keyService) {
    this.keyService = keyService;
  }

  @Override
  public void afterPropertiesSet() throws Exception {
    PublicKey publicKey = keyService.query(KEY_NAME, KeyType.RSA_PUBLIC);

    if (publicKey == null) {
      keyService.regenerate(KEY_NAME);
      return;
    }

    PrivateKey privateKey = keyService.query(KEY_NAME, KeyType.RSA_PRIVATE);
    if (privateKey == null) {
      keyService.regenerate(KEY_NAME);
    }
  }
}
